﻿using Prism.Commands;
using Prism.Events;
using Prism.Mvvm;
using System;
using System.Collections.Generic;
using System.Text;

namespace ModuleA.ViewModels
{
    public class ViewAViewModel : BindableBase
    {
        private string title;

        public DelegateCommand ChangeTitle { get; private set; }

        public DelegateCommand Subscribe { get; private set; }
        public DelegateCommand Publish { get; private set; }
        public DelegateCommand UnSubscribe { get; private set; }

        public ViewAViewModel(IEventAggregator eventAggregator)
        {
            Title = "View A";
            ChangeTitle = new DelegateCommand(
                () => { 
                    Title = "执行了Command！"; 
                });
            //订阅
            Subscribe = new DelegateCommand(()=> 
            {
                eventAggregator.GetEvent<MessageEvent>().Subscribe(OnMessageRecevied,ThreadOption.PublisherThread,false,
                    msg=>{
                        //进行了条件过滤
                        if ("你好呀！".Equals(msg))
                        {
                            return false;
                        }
                        return true;
                    });
            });
            //发布事件
            Publish = new DelegateCommand(()=> 
            {
                eventAggregator.GetEvent<MessageEvent>().Publish("你好呀！");
            });
            //取消发布
            UnSubscribe = new DelegateCommand(()=> 
            {
                eventAggregator.GetEvent<MessageEvent>().Unsubscribe(OnMessageRecevied);
            });
        }

        private void OnMessageRecevied(string obj)
        {
            Title += $"发布[{obj}]\r\n";
        }

        public string Title
        {
            get { return title; }
            set { title = value; RaisePropertyChanged(); }
        }
    }

    internal class MessageEvent:PubSubEvent<string>
    {

    }
}
